package com.hyg.topic;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by huangyugen on 2018/07/19
 **/
public class ReceiveLogsTopic1 {
    private static final String EXCHANGE_NAME = "topic_logs";
    private static final String HOST = "192.168.1.91";

    public static void main(String[] argv) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
//		声明一个匹配模式的交换器
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        String queueName = channel.queueDeclare().getQueue();
//      路由关键字
//      如果消费者端的路由关键字只使用【#】来匹配消息，在匹配【topic】模式下，
//      它会变成一个分发【fanout】模式，接收所有消息。
//      如果消费者端的路由关键字中没有【#】或者【*】，它就变成直连【direct】模式来工作。
        String[] routingKeys = new String[]{"*.orange.*"};
//		绑定路由关键字
        for (String bindingKey : routingKeys) {
            channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
            System.out.println("ReceiveLogsTopic1 exchange:" + EXCHANGE_NAME + ", queue:" + queueName + ", BindRoutingKey:" + bindingKey);
        }
        System.out.println("ReceiveLogsTopic1 [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("ReceiveLogsTopic1 [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");

                System.out.println("===========================");}
        };
        channel.basicConsume(queueName, true, consumer);

    }
}
